﻿
namespace Admin.NET.Core.Service;
public class CodeGenByTable
{
    //根据表进行代码生成
    public static void CreateByEntity(IViewEngine _viewEngine, DbTableInfo dbTableInfo, List<DbColumnOutput> dbColumnInfos, CreateEntityInput input)
    {
        // 根据input.FileName组装模板路径
        var templatePath = Path.Combine(App.WebHostEnvironment.WebRootPath, "template");
        templatePath = Path.Combine(templatePath, input.FileName + ".vm");
        // 根据input.FileName组装生成的文件存放路径
        var targetPath = Path.Combine(new DirectoryInfo(App.WebHostEnvironment.ContentRootPath).Parent.FullName, input.Position);
        var fileName = input.EntityName + input.FileName.Replace("Entity", "");
        targetPath = Path.Combine(targetPath, fileName);

        // 读取模板
        var tContent = File.ReadAllText(templatePath);
        // 生成代码
        var tResult = _viewEngine.RunCompileFromCached(tContent, new
        {
            NameSpace = $"{input.Position}.Entity",
            input.TableName,
            input.EntityName,
            BaseClassName = string.IsNullOrWhiteSpace(input.BaseClassName) ? "" : $" : {input.BaseClassName}",
            input.ConfigId,
            dbTableInfo.Description,
            TableField = dbColumnInfos
        });
        // 保存代码文件
        File.WriteAllText(targetPath, tResult, Encoding.UTF8);
    }
}
